package com.it.hanzhongtravelv1.service;

import com.it.hanzhongtravelv1.dto.FAQDTO;
import com.it.hanzhongtravelv1.entity.FAQ;
import com.it.hanzhongtravelv1.repository.FAQRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class FAQService {
    
    @Autowired
    private FAQRepository faqRepository;
    
    /**
     * 获取所有FAQ，按分类和排序顺序排列
     */
    public List<FAQDTO> getAllFAQs() {
        return faqRepository.findAllByOrderByCategoryAscSortOrderAsc()
                .stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    /**
     * 根据分类获取FAQ
     */
    public List<FAQDTO> getFAQsByCategory(String category) {
        return faqRepository.findByCategoryOrderBySortOrderAsc(category)
                .stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    /**
     * 搜索FAQ
     */
    public List<FAQDTO> searchFAQs(String keyword) {
        return faqRepository.findByQuestionContainingOrAnswerContainingOrderBySortOrderAsc(keyword, keyword)
                .stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    /**
     * 新增或更新FAQ
     */
    public FAQDTO saveFAQ(FAQ faq) {
        FAQ savedFaq = faqRepository.save(faq);
        return convertToDTO(savedFaq);
    }

    /**
     * 删除FAQ
     */
    public void deleteFAQ(Long id) {
        faqRepository.deleteById(id);
    }
    
    /**
     * 实体转DTO
     */
    private FAQDTO convertToDTO(FAQ faq) {
        return new FAQDTO(
            faq.getId(),
            faq.getQuestion(),
            faq.getAnswer(),
            faq.getCategory(),
            faq.getSortOrder()
        );
    }
} 